package app

import (
	"APT/internal/dao"
	"APT/internal/library/contexts"
	"APT/internal/model/entity"
	"APT/internal/model/input/input_basics"
	"APT/internal/service"
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"

	"APT/api/app/member"
)

func (c *ControllerMember) Cancel(ctx context.Context, req *member.CancelReq) (res *member.CancelRes, err error) {
	var (
		MemberUser      = contexts.GetMemberUser(ctx)
		PmsMemberCancel *entity.PmsMemberCancel
		InsertData      *entity.PmsMemberCancel
		Config          *input_basics.GetConfigModel
	)
	if err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 根据会员ID找到会员注销记录
		if err = dao.PmsMemberCancel.Ctx(ctx).TX(tx).
			Where(g.Map{
				dao.PmsMemberCancel.Columns().MemberId: MemberUser.Id,
			}).
			WhereIn(dao.PmsMemberCancel.Columns().AuditStatus, []int{1, 2}).OrderDesc(dao.PmsMemberCancel.Columns().Id).
			Scan(&PmsMemberCancel); err != nil && !errors.Is(err, sql.ErrNoRows) {
			return
		}

		if !g.IsEmpty(PmsMemberCancel) {
			err = gerror.New("您已申请注销会员，请勿重复申请！")
			return
		}

		// 获取会员注销设置
		if Config, err = service.BasicsConfig().GetConfigByGroup(ctx, &input_basics.GetConfigInp{
			Group: "membercancelsetting",
		}); err != nil {
			err = gerror.Wrap(err, "未找到注销设置！")
			return
		}

		IsEnableCancel := Config.List["isEnableCancel"]
		IsCancelAudit := Config.List["isCancelAudit"]
		if IsEnableCancel != 1 {
			err = gerror.New("不可注销会员账号！")
			return
		}

		if IsCancelAudit == 1 {
			InsertData = &entity.PmsMemberCancel{
				MemberId:     gvar.New(MemberUser.Id).Uint(),
				MemberNo:     MemberUser.MemberNo,
				Phone:        MemberUser.Phone,
				PhoneArea:    MemberUser.PhoneArea,
				Mail:         MemberUser.Mail,
				CancelReason: req.CancelReason,
			}
		} else {
			// 无需审核
			InsertData = &entity.PmsMemberCancel{
				MemberId:     gvar.New(MemberUser.Id).Uint(),
				MemberNo:     MemberUser.MemberNo,
				Phone:        MemberUser.Phone,
				PhoneArea:    MemberUser.PhoneArea,
				Mail:         MemberUser.Mail,
				CancelReason: req.CancelReason,
				AuditStatus:  2,
				AuditTime:    gtime.Now(),
				AuditReason:  "用户申请注销自动审核成功",
				OperatorId:   0,
			}

			// 删除会员信息
			if _, err = dao.PmsMember.Ctx(ctx).TX(tx).WherePri(MemberUser.Id).Delete(); err != nil {
				err = gerror.Wrap(err, "注销会员失败，请稍后重试！")
				return
			}
		}

		// 写入会员注销记录
		if _, err = dao.PmsMemberCancel.Ctx(ctx).TX(tx).Data(InsertData).OmitEmptyData().Insert(); err != nil {
			err = gerror.Wrap(err, "申请注销失败，请稍后重试！")
			return
		}
		return
	}); err != nil {
		return
	}
	return
}
